package XML.DOM;


import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.util.Scanner;

public class Test {
    Document document = null;

    public void getDocument() throws Exception {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        document = documentBuilder.parse(this.getClass().getResourceAsStream("/XML/DOM/student.xml"));
    }

    public void show() {
        NodeList students = document.getElementsByTagName("student");
        for (int i = 0; i < students.getLength(); i++) {
            Node student = students.item(i);
            Element studentElement = (Element) student;
            String id = studentElement.getAttribute("id");
            System.out.print("id:" + id + "\t\t");
            //获取孩子
            NodeList childNodes = student.getChildNodes();
            for (int j = 0; j < childNodes.getLength(); j++) {
                Node child = childNodes.item(j);
                if (child.getNodeType() == 1) {
                    Element element = (Element) child;
                    String nodeName = element.getNodeName();
                    String nodeValue = element.getFirstChild().getNodeValue();
                    System.out.print(nodeName + ":" + nodeValue + "\t\t");
                }
            }
            System.out.println();
        }
    }

    public void add(int id1, String name1, int age1) throws Exception {
        Element name = document.createElement("name");
        name.setTextContent(name1);
        Element age = document.createElement("age");
        age.setTextContent(age1 + "");
        Element student = document.createElement("student");
        student.setAttribute("id", id1 + "");  //设置属性
        student.appendChild(name);
        student.appendChild(age);
        Node students = document.getElementsByTagName("students").item(0).appendChild(student);
        System.out.println("添加成功！");
        save2();
    }

    public void remove(int id1) throws Exception{
        Integer j = id1;
        boolean index = false;
        NodeList students = document.getElementsByTagName("student");
        for (int i = 0; i < students.getLength(); i++) {
            Node student = students.item(i);
            Element studentElement = (Element) student;
            String id = studentElement.getAttribute("id");
            if (j.toString().equals(id)) {
                student.getParentNode().removeChild(student);
                System.out.println("删除成功！");
                save2();
                index = true;
                break;
            }
//            if(j.toString().equals(id)){
//                ((Element) student).setAttribute();              修改属性
//                student.setTextContent("??");                    修改内容
//            }
        }
        if (!index) {
            System.out.println("删除失败！");
        }
    }

    public void search(int id1) {
        boolean index = false;
        Integer in = id1;
        NodeList students = document.getElementsByTagName("student");
        for (int i = 0; i < students.getLength(); i++) {
            Node student = students.item(i);
            Element studentElement = (Element) student;
            String id = studentElement.getAttribute("id");
            if (in.toString().equals(id)) {
                NodeList childNodes = student.getChildNodes();
                for (int j = 0; j < childNodes.getLength(); j++) {
                    Node child = childNodes.item(j);
                    if (child.getNodeType() == 1) {
                        Element element = (Element) child;
                        System.out.println(element.getTextContent()); //显示所有孩子
                    }
                }
                index = true;
            }
        }
        if (!index) {
            System.out.println("没有找到");
        }
    }
    public void save() throws Exception{
        String s = "F:/J19/Test1/src/XML/DOM/student.xml";
        OutputFormat format= new OutputFormat(document);//写入格式
        format.setIndent(2);//缩进两个单位
        format.setIndenting(true);//开启缩进
        XMLSerializer serializer=new XMLSerializer(new FileWriter(s),format);//写入的位置 以及格式
        serializer.serialize(document);

    }
    public void save2() throws Exception {
        String s = "F:\\J19\\Test1\\src\\XML\\DOM\\student.xml";
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();
        DOMSource domSource = new DOMSource(document);
        StreamResult result = new StreamResult(new FileOutputStream(s));
        transformer.transform(domSource,result);
    }
    public static void main(String[] args) throws Exception {
        Test test = new Test();
        test.getDocument();
        Scanner input = new Scanner(System.in);
        while (true) {
            System.out.println("1、添加学生");
            System.out.println("2、查找学生");
            System.out.println("3、查看所有学生");
            System.out.println("4、删除学生");
            System.out.println("5、退出");
            System.out.println("选择？");
            switch (input.nextInt()) {
                case 1:
                    System.out.println("请输入学号：");
                    int id = input.nextInt();
                    System.out.println("请输入姓名：");
                    String name = input.next();
                    System.out.println("请输入年龄：");
                    int age = input.nextInt();
                    test.add(id,name,age);
                    break;
                case 2:
                    System.out.println("请输入学号：");
                    test.search(input.nextInt());
                    break;
                case 3:
                    test.show();break;
                case 4:
                    System.out.println("请输入学号：");
                    test.remove(input.nextInt());
                    break;
                case 5:
                    System.out.println("告辞！");
                    System.exit(1);
            }
        }
    }
}
